﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Forms.Core;
using Umbraco.Forms.Core.Attributes;
using Umbraco.Forms.Data;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.datatype;
using Umbraco.Forms.Data.Storage;

namespace ContourStrikesAgain.WorkflowTypes
{
    public class SaveAsUmbracoMember: WorkflowType {
    
        [Setting("Member Type", description = "Map member type", 
            control = "ContourStrikesAgain.FieldSettingTypes.MemberPropertyMapper",
            assembly="ContourStrikesAgain")]
        public string Fields { get; set; }

       
        public SaveAsUmbracoMember()
        {
            this.Id = new Guid("44A4007D-0CDA-41E3-9F8E-29F49EBF3FA8");
            this.Name = "Save as umbraco member";
            this.Description = "Saves the form values as an umbraco member with a specific type";
            
        }

        public override Umbraco.Forms.Core.Enums.WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
        {
            Dictionary<string, string> mappings = new Dictionary<string, string>();
            int mtId = 0;

            string nameMapping = "NodeName";
            string loginMapping = "Login";
            string emailMapping = "Email";
            string passwordMapping = "Password";

            string[] array = Fields.Trim().Split('|');

            foreach (string s in array)
            {
                string[] a = s.Trim().Split(',');

                if (a.Count() == 1 && s.Trim().Length >= 4)
                {

                    if (mtId == 0)
                        int.TryParse(s.Trim(), out mtId);

                }
                else if (a.Count() == 3)
                {

                    string mapping = "";

                    if (!string.IsNullOrEmpty(a[2]))
                        mapping = record.RecordFields[new Guid(a[2])].ValuesAsString();
                    else if (!string.IsNullOrEmpty(a[1]))
                        mapping = StringHelper.ParsePlaceHolders(e.Context, record, a[1]);
                    //TODO change _parseAttribute into a helper by itself

                    if ((!string.IsNullOrEmpty(mapping)))
                    {
                        if (a[0] == "__defaultname")
                            nameMapping = mapping;
                        else if (a[0] == "__defaultlogin")
                            loginMapping = mapping;
                        else if (a[0] == "__defaultemail")
                            emailMapping = mapping;
                        else if (a[0] == "__defaultpassword")
                            passwordMapping = mapping;
                        else
                        {
                            mappings.Add(a[0], mapping);
                            LogHelper.Debug(a[0] + " " + mapping);
                        }
                    }
                }
            }

            MemberType mt = new MemberType(mtId);

            if (mt != null)
            {
                Member m = Member.MakeNew(nameMapping, loginMapping, emailMapping, mt, new umbraco.BusinessLogic.User(0));
                m.Password = passwordMapping;

                foreach (Property p in m.getProperties)
                {

                    try
                    {

                        if (mappings.ContainsKey(p.PropertyType.Alias))
                        {
                            switch (((BaseDataType)p.PropertyType.DataTypeDefinition.DataType).DBType)
                            {
                                case DBTypes.Date:
                                    p.Value = DateTime.Parse(mappings[p.PropertyType.Alias]);
                                    break;
                                case DBTypes.Integer:
                                    string v = mappings[p.PropertyType.Alias];
                                    if (v.ToLower() == "true" || v.ToLower() == "false")
                                        p.Value = bool.Parse(v);
                                    else
                                        p.Value = int.Parse(mappings[p.PropertyType.Alias]);
                                    break;
                                default:
                                    p.Value = mappings[p.PropertyType.Alias];
                                    break;
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        LogHelper.Debug(ex.ToString());
                    }
                }

                m.XmlGenerate(new System.Xml.XmlDocument());
                m.Save();


               //store record id and member id

                SettingsStorage ss = new SettingsStorage();
                ss.InsertSetting(record.Id, "SaveAsUmbracoMemberCreatedMemberID", m.Id.ToString());
                ss.Dispose();

            }

            return Umbraco.Forms.Core.Enums.WorkflowExecutionStatus.Completed;
        }

        public override List<Exception> ValidateSettings()
        {
            return new List<Exception>();
        }
    }
}